<template>
	<div>
		<BreadCrumb pathOne="内容管理" pathTwo="文章管理"></BreadCrumb>
		<div>
			<el-form :inline="true">
				<el-form-item label="文章名" size="large">
					<el-input clearable size="large" v-model="searchName" style="width: 240px" placeholder="请输入文章名" />
				</el-form-item>
				<el-form-item label="咨询师作者" size="large">
					<el-select @clear="consultId = ''" clearable v-model="consultId" placeholder="无" size="large"
						style="width: 240px">
						<el-option v-for="(item, index) in AllAuthor" :value="item.id" :label="item.consultName" />
					</el-select>
				</el-form-item>
				<el-form-item label="选择分类" size="large">
					<el-select @clear="classifyId = ''" clearable v-model="classifyId" placeholder="无" size="large"
						style="width: 240px">
						<el-option v-for="(item, index) in AllClassify" :value="item.id" :label="item.classifyName" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="query" size="large">搜索</el-button>
					<el-button type="success" @click="batchRecover" size="large">批量恢复</el-button>
					<el-button type="danger" size="large" @click="batchDelete">批量删除</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div>
			<el-alert title="回收站中的文件只能保存15天" type="warning" show-icon :closable="false" center />

			<el-table :data="tableData" style="width: 100%;margin-top: 10px;" border
				:header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }"
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" width="40" />
				<el-table-column fixed prop="id" label="id" width="50" />
				<el-table-column prop="articleName" label="文章名" width="110" show-overflow-tooltip />
				<el-table-column prop="articleIntroduction" label="文章简介" width="110" show-overflow-tooltip />
				<el-table-column prop="consultName" label="咨询师名" width="90" />
				<el-table-column label="缩略图" width="120">
					<template #default="scope">
						<el-avatar shape="square" size="large" :src="scope.row.url" />
					</template>
				</el-table-column>
				<el-table-column prop="count" label="阅读量" width="70" />
				<el-table-column prop="classifyName" label="所属分类" width="90" />
				<el-table-column prop="articleTime" label="创建时间" width="180" />
				<el-table-column prop="deleteTime" label="删除时间" width="180" />

				<el-table-column label="剩余保留时间" width="140">
					<template #default="scope">
						<span :class="scope.row.remainingDays <= 0 ? 'text-danger font-bold' : 'text-success'">
							{{ scope.row.remainingDays <= 0 ? '已过期' : `${scope.row.remainingDays}天` }} </span>
					</template>
				</el-table-column>
				<el-table-column label="审核状态" width="110">
					<template #default="scope">
						<el-tag type="warning" v-if="scope.row.status == 0">审核中</el-tag>
						<el-tag type="success" v-else-if="scope.row.status == 1">已审核</el-tag>
						<el-tag type="danger" v-else>审核未通过</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="状态" width="70">
					<template #default="scope">
						<el-tag type="success" v-if="scope.row.del == 0">正常</el-tag>
						<el-tag type="danger" v-else>已删除</el-tag>
					</template>
				</el-table-column>
				<el-table-column fixed="right" label="操作" width="270">
					<template #default="scope">
						<el-button size="small" type="success" @click="add(scope.row.id)">恢复</el-button>
						<el-button size="small" type="danger" @click="remove(scope.row.id)">彻底删除</el-button>
						<!-- <el-button size="small" type="primary"
							@click="searchArticleDetails(scope.row.id)">查看详情内容</el-button> -->
					</template>
				</el-table-column>
			</el-table>
		</div>
		<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
			:size="size" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
			@current-change="handleCurrentChange" />
		<el-dialog v-model="dialogArticleDetails" title="内容详情" width="700" style="margin-bottom: 60px;"
			@close="handleClose">
			<el-form-item label="" label-width="auto" label-position='top'>
				<QuillEditor :value="form.content" @updateValue="getMsg"></QuillEditor>
			</el-form-item>
		</el-dialog>
	</div>
</template>

<script setup>
	import {
		getCurrentInstance,
		onMounted,
		reactive,
		ref
	} from 'vue'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		Plus
	} from '@element-plus/icons-vue'
	import BreadCrumb from "../../components/BreadCrumb.vue"
	import QuillEditor from "../../components/QuillEditor.vue"
	const getMsg = (val) => {
		// console.log('form.value.articleDetails',form.value.articleDetails);
		form.value.articleDetails = val
		console.log('监听的值：', val);
	}
	const AllAuthor = ref([])
	const AllClassify = ref([])
	const axios = getCurrentInstance().appContext.config.globalProperties.axios;
	const getAllAuthor = () => {
		axios.get(`/consult`).then(resp => {
			AllAuthor.value = resp.data
		})
	}

	const getAllClassify = () => {
		axios.get(`articleClassify/find`).then(resp => {
			AllClassify.value = resp.data
		})
	}
	const tableData = ref([])
	const consultId = ref('')
	const classifyId = ref('')
	const query = () => {
		axios.get( //article/findArticlePage
			`article/findArticlePageDelelete?articleName=${searchName.value}&consultId=${consultId.value}&classifyId=${classifyId.value}&pageNum=${currentPage.value}&pageSize=${pageSize.value}`,
		).then(resp => {
			// 这里要注意 resp.data.data
			tableData.value = resp.data.list
			total.value = resp.data.total

			tableData.value.forEach(item => {
				item.url = item.url
				// 2. 计算剩余保留时间（核心新增逻辑）
				if (item.deleteTime) { // 确保后端返回了删除时间
					const deleteDate = new Date(item.deleteTime);
					const now = new Date();
					// 计算15天后的过期时间
					const expireDate = new Date(deleteDate);
					expireDate.setDate(deleteDate.getDate() + 14);

					// 计算剩余天数（向上取整）
					const diffMs = expireDate - now;
					const remainingDays = Math.ceil(diffMs / (1000 * 60 * 60 * 24));

					// 给每条数据添加剩余天数属性
					item.remainingDays = remainingDays;
				} else {
					// 若后端未返回删除时间，默认标记为已过期（避免异常）
					item.remainingDays = 0;
				}
			})

		})
	}
	const currentPage = ref(1) // 当前页
	const pageSize = ref(10) // 每页显示条目数
	const size = 'default' // 分页大小
	const total = ref(0)
	const handleSizeChange = (val) => {
		pageSize.value = val;
		query();
	}
	const handleCurrentChange = (val) => {
		currentPage.value = val
		query();
	}
	const searchName = ref('')
	const dialogArticleDetails = ref(false)
	// const articleClassifyName = ref('')
	const handleClose = () => {
		form.value = {
			id: "",
			articleName: "",
			articleIntroduction: "",
			consultId: "",
			url: "",
			content: "",
			count: "",
			classifyId: "",
			classifyName: "",
			articleTime: "",
			status: "",
			articleDel: "",
			consultName: ""
		}
	}
	const searchArticleDetails = (id) => {
		dialogArticleDetails.value = true
		axios.get(`/article/findById/${id}`).then(resp => {
			form.value = resp.data
			// resp.data.url为相对路径，展示时拼接完整路径
			imageUrl.value = resp.data.url
		})
	}
	const form = ref({
		id: "",
		articleName: "",
		articleIntroduction: "",
		consultId: "",
		url: "",
		content: "",
		count: "",
		classifyId: "",
		classifyName: "",
		articleTime: "",
		status: "",
		articleDel: "",
		consultName: ""
	})
	const add = (id) => {
		console.log('当前行的数据', id);
		ElMessageBox.confirm(
				'此操作将恢复选择的文件, 是否继续?',
				'提示', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				axios.put(`/article/recover/${id}`).then((resp) => {
					console.log('恢复后：', resp);
					if (resp.code == 200) {
						ElMessage({
							message: '恢复成功',
							type: 'success',
						})
					} else {
						ElMessage.error('恢复失败')
					}
				}).finally(() => {
					query();
				});
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消恢复',
				})
			})
	}

	const remove = (id) => {
		console.log('当前行的数据', id);
		ElMessageBox.confirm(
				'此操作将永久删除该文件, 是否继续?',
				'提示', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				axios.delete(`/article/removecompletely/${id}`).then((resp) => {
					console.log('删除后：', resp);
					if (resp.code == 200) {
						ElMessage({
							message: '删除成功',
							type: 'success',
						})
					} else {
						ElMessage.error('删除失败')
					}
				}).finally(() => {
					query();
				});
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})
	}

	const ids = ref([]) // 改为数组
	const handleSelectionChange = (selection) => {
		ids.value = selection.map(item => item.id)
		console.log('批量操作的ids为:', ids.value)
	}

	const batchRecover = () => {
		if (!ids.value.length) {
			ElMessage.info('请选择要恢复的数据')
			return
		}
		ElMessageBox.confirm('此操作将恢复选择的文件, 是否继续?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			axios.put('/article/recoverBatch', ids.value).then(res => {
				ElMessage.success('恢复成功')
				query();
			})
		}).catch(() => {
			ElMessage.info('已取消恢复')
		}).finally(() => {
			query();
		});
	}

	const batchDelete = () => {
		if (!ids.value.length) {
			ElMessage.info('请选择要删除的数据')
			return
		}
		ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			axios.delete('/article/removeBatchCompletely', {
				data: ids.value
			}).then(res => {
				ElMessage.success('删除成功')
				query();
			})
		}).catch(() => {
			ElMessage.info('已取消删除')
		}).finally(() => {
			query();
		});
	}

	onMounted(() => {
		query()
		getAllAuthor()
		getAllClassify()
	})
</script>

<style scoped>
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.text-danger {
		color: var(--el-color-danger);
	}

	.text-success {
		color: var(--el-color-success);
	}

	.font-bold {
		font-weight: bold;
	}
</style>